﻿using LargeFilesSample.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace LargeFilesSample.Controllers
{
    [Route("files")]
    [ApiController]
    public class FileIndexController : ControllerBase
    {
        private readonly IServiceProvider _provider;

        // 数据库上下文 dbContext
        private readonly DocumentStorageCenterDbContext _dbContext;

        private readonly ILogger<FileIndexController> _logger;

        public FileIndexController(ILogger<FileIndexController> logger,
            IServiceProvider provider,
            DocumentStorageCenterDbContext dbContext)
        {
            _logger = logger;
            _provider = provider;
            _dbContext = dbContext;
        }

        [HttpGet]
        [AllowAnonymous]
        public ActionResult<PageableFileList> IndexByPage(int page = 0, int size = 5)
        {
            // 1.【入参校验】
            const int MAX_ITEMS_PER_PAGE = 50;
            if (!(page >= 0 && size >= 1 && size <= MAX_ITEMS_PER_PAGE))
            {
                string reason = $"Error: page={page}, size={size}: 页码参数无效! 要求page>=0 && size>=1 && size<={MAX_ITEMS_PER_PAGE}";
                var badResponse = new PageableFileList()
                {
                    Message = reason,
                    Content = new List<TmpFile>(),
                };
                return BadRequest(badResponse);
            }
            _logger.LogInformation("============");
            // 2. 【数据库查询】
            var fileRepository = _dbContext.FileRepository;
            // 2.1 总计多少条数据
            int totalElements = fileRepository.Count();
            // 2.2 总计页数
            int totalPages = totalElements / size;
            // 2.3 筛选当前页码
            List<TmpFile> selected = fileRepository.OrderBy(file => file.Id).Skip(page * size).Take(size).ToList();//TODO: 重构API设计，避免页码>1000时SQL查询效率过低
            var result = new PageableFileList()
            {
                Message = "Success",
                Content = selected,
                TotalElements = totalElements,
                TotalPages = totalPages,
                NumberOfElements = selected.Count
            };
            return Ok(result);
        }

        public class PageableFileList : GenericPageableList<TmpFile>
        {
        }

        [HttpGet("{id}")]
        [AllowAnonymous]
        public async Task<IActionResult> FindById(int id)
        {
            _logger.LogInformation("============ 查询单个文件 =============");
            var fileList = _dbContext.FileRepository;
            var selected = fileList.Where(file => id == file.Id);
            return await Task.FromResult(Ok(selected));
        }
    }
}
